package com.yozinga.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;

import com.google.android.gms.internal.ac;
import com.google.gson.Gson;

public class HttpRequestCaller {

	public static final int GET = 0; 
	public static final int POST = 1;
	public ServiceResponse GetServiceResponse(String url,String id,int method,String connectionType,Bundle requestBody,String action){

		HttpURLConnection conn = null;
		ServiceResponse serviceResponse = new ServiceResponse();
		HttpClient httpClient;
		switch (method) {
		case GET:
			try{
				if(id!=null)
					url = url + id;
				Log.i("Today","GET Url is : "+url);
				httpClient = new DefaultHttpClient();
				HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
				HttpGet http = new HttpGet(url);
				HttpResponse response = null;
				response = httpClient.execute(http);
				Log.i("Today","Response code :"+response.getStatusLine().getStatusCode());
				serviceResponse.responseHttpStatusCode = response.getStatusLine().getStatusCode();
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					InputStream instream = entity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
					StringBuilder sb = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						sb.append(line);
					}
					String	responseJsonString = sb.toString();
					serviceResponse.response = responseJsonString;
					Log.i("Today", "Service Response is: " + sb.toString());
				}	
			}catch (Exception e) {
			}

			break;
		case POST:
			try
			{
				Log.i("Today","Url is : "+url);
				URL myurl = new URL(url);
				conn = (HttpURLConnection) myurl.openConnection();

				conn.setDoInput(true);
				conn.setUseCaches(false);
				conn.setDoOutput(true);

				conn.setRequestMethod("POST");
				if(action.equals("com.yozinga.redeemoffer")){
					conn.setRequestProperty("Content-type", "application/json");
					//conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
				}else{
					conn.setRequestProperty("Content-type", "application/json");
				}
				conn.setConnectTimeout(6000);
				String gsonfile;
				if(requestBody!=null){
					DataOutputStream printout = new DataOutputStream(conn.getOutputStream());
					LinkedHashMap<String,Object> json_array = new LinkedHashMap<String,Object>();
					if(action.equals("com.yozinga.redeemoffer")){
						//conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
						String appId = "913b970d-a81c-4fbe-a64b-f5eff30ceac2";
						json_array.put("DeviceId", requestBody.getString("DeviceId"));
						json_array.put("OfferId", requestBody.getString("OfferId"));
						json_array.put("RedeemCode", /*requestBody.getString("RedeemCode")*/1506359440);
						json_array.put("Offer", null);
						json_array.put("AppId",appId);

						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
						Date date = new Date();
						System.out.println(dateFormat.format(date));

						json_array.put("DateProcessed",dateFormat.format(date));
						//String deviceId = requestBody.getString("DeviceId");
						//String offerId = requestBody.getString("OfferId");
						//String redeemCode =  requestBody.getString("RedeemCode");

						//gsonfile = "DeviceId="+deviceId+"&OfferId="+offerId+"&RedeemCode="+redeemCode+"&Offer="+"null"+"&AppId="
						//+appId+"&DateProcessed="+"2013-08-10T06:55:19.7229404Z";

						Gson gson = new Gson();
						gsonfile = gson.toJson(json_array);
						Log.i("Today","Boday is: "+gsonfile);
					}else if(action.equalsIgnoreCase("com.yozinga.reviewoffer")){
						/*bundle.putString("DeviceId", deviceid);
						bundle.putString("OfferId", offerId);
						bundle.putString("Description", Desc);
						bundle.putFloat("rating", rating);*/
						
						json_array.put("DeviceId", requestBody.getString("DeviceId"));
						json_array.put("OfferId", requestBody.getString("OfferId"));
						
						
						json_array.put("Rating", requestBody.getFloat("rating"));
						json_array.put("Description",requestBody.getString("Description"));

						Gson gson = new Gson();
						gsonfile = gson.toJson(json_array);
						Log.i("Today","Boday is: "+gsonfile);


					}else{
						json_array.put("DeviceId", requestBody.getString("DeviceId"));
						json_array.put("DeviceType", requestBody.getString("DeviceType"));
						json_array.put("Latitude", requestBody.getString("Latitude"));
						json_array.put("Longitude",  requestBody.getString("Longitude"));
						json_array.put("PushNotification",  requestBody.getString("PushNotification"));
						json_array.put("StartTime",  requestBody.getString("StartTime"));
						json_array.put("EndTime",  requestBody.getString("EndTime"));
						Gson gson = new Gson();
						gsonfile = gson.toJson(json_array);
						Log.i("Today","Boday is: "+gsonfile);
					}



					printout.writeBytes(gsonfile);
					printout.flush();
					printout.close();
				}


				int responseCode = conn.getResponseCode();
				serviceResponse.responseHttpStatusCode = responseCode;
				Log.i("Today","Response code :"+conn.getResponseCode());

				String 	responseJsonString = null;
				if(responseCode == HttpsURLConnection.HTTP_OK || responseCode == 201) {
					if (conn.getInputStream() != null) {
						// A Simple JSON Response Read
						InputStream instream = conn.getInputStream();
						BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
						StringBuilder sbResponseBody = new StringBuilder();
						String line; 
						while ((line = reader.readLine()) != null) {
							sbResponseBody.append(line);
						}
						responseJsonString = sbResponseBody.toString();
						Log.i("Today","responseJsonString "+responseJsonString);
					}				
				}

				serviceResponse.response = responseJsonString;
			} 
			catch (IOException e) 
			{
				Log.i("Today","IOException"+e.getMessage());
				e.printStackTrace();
			}
			catch(Exception e){
				Log.i("Today","Exception"+e.getMessage());
			}
			finally{
				conn.disconnect();
			}
			break;

		default:
			break;
		}

		return serviceResponse;
	}

	public class ServiceResponse{
		public int responseHttpStatusCode;
		public String response;
	}	
}
